<template>
	<view class="">
		<view class="main-content" v-if="applyStatus == 2">
			<scroll-view scroll-y :style="{height: scrollHeight}" class="list-box form-data">
				<!-- <text class="title">我的机构</text> -->
				<uni-forms ref="masterEnterForm" :modelValue="FormData" :rules="rules" label-width="80">
					<uni-forms-item label="公司名称" name="companyName" required>
						<input type="text" placeholder="请输入公司名称" v-model="FormData.companyName"
							style="text-align: right;" />
					</uni-forms-item>
					<uni-forms-item label="负责人姓名" name="contact">
						<input type="text" placeholder="请输入负责人姓名" v-model="FormData.contact"
							style="text-align: right;" />
					</uni-forms-item>
					<uni-forms-item label="负责人电话" name="phoneNumber">
						<input type="number" placeholder="请输入负责人电话" v-model="FormData.phoneNumber"
							style="text-align: right;" />
					</uni-forms-item>
					<uni-forms-item label="选择地址" name="province">
						<view class="row-end-1" @click="show = true">
							<view style="text-align: right;">
								<text class="placeholder-class" v-if="region == ''">请选择</text>
								<text v-else style="font-size: 28rpx;">{{region}}</text>
							</view>
							<uni-icons type="right" color="#666" size="36rpx"></uni-icons>
						</view>
					</uni-forms-item>
					<uni-forms-item label="详细地址" name="address">
						<input type="text" placeholder="请输入地址" v-model="FormData.address" style="text-align: right;" />
					</uni-forms-item>
					<uni-forms-item label="公司简介" name="intro">
						<input type="text" placeholder="请输入地址" v-model="FormData.intro" style="text-align: right;" />
					</uni-forms-item>
					<uni-forms-item label="公司描述" name="remark">
						<input type="text" placeholder="请输入地址" v-model="FormData.remark" style="text-align: right;" />
					</uni-forms-item>
				</uni-forms>
				<view class="form-item-vertical">
					<view class="label">
						身份证正面照片
					</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.idCardFront" @afterRead="afterRead" @delete="deletePic"
							name="idCardFront" multiple :maxCount="1" :previewFullImage="true" width="198rpx"
							height="198rpx">
							<view class="upload-after">
								<u-icon name="plus" size="60rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
				<view class="form-item-vertical">
					<view class="label">身份证反面照片</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.idCardBack" @afterRead="afterRead" @delete="deletePic"
							name="idCardBack" multiple :maxCount="1" :previewFullImage="true" width="198rpx"
							height="198rpx">
							<view class="upload-after">
								<u-icon name="plus" size="60rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
				<view class="form-item-vertical">
					<view class="label">营业执照</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.businessLicense" @afterRead="afterRead" @delete="deletePic"
							name="businessLicense" multiple :previewFullImage="true" width="198rpx" height="198rpx"
							:maxCount="1">
							<view class="upload-after">
								<u-icon name="file-text" size="100rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
				<view class="form-item-vertical">
					<view class="label">公司logo</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.logo" @afterRead="afterRead" @delete="deletePic" name="logo"
							multiple :previewFullImage="true" width="198rpx" height="198rpx" :maxCount="1">
							<view class="upload-after">
								<u-icon name="plus" size="100rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
				<view class="form-item-vertical">
					<view class="label">公司公章</view>
					<view class="upload-box">
						<u-upload :fileList="fileImage.commonSeal" @afterRead="afterRead" @delete="deletePic"
							name="commonSeal" multiple :previewFullImage="true" width="198rpx" height="198rpx"
							:maxCount="1">
							<view class="upload-after">
								<u-icon name="plus" size="100rpx" color="#eee"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
			</scroll-view>
			<you-bottom-btn :btnConfig="bottomBtnConfig" @formSubmit="formSubmit" @testReport="testReport">
			</you-bottom-btn>
		</view>
		<apply-for image="../../../static/images/home/organization.jpg" :title="'公司名称'" :placeholder="'请输入公司名称'"
			:color="'#fff'" v-else-if="applyStatus == 0 || applyStatus == 3" @applySuccess="applySuccess"></apply-for>

		<!-- 选择城市 -->
		<u-picker :show="show" ref="uPicker" :columns="cityColumns" :defaultIndex="defaultIndex" @confirm="cityConfirm"
			keyName="cname" @change="changeHandler" @cancel="show = false"></u-picker>
	</view>
</template>

<script>
	import Home from '@/api/home'
	import Apply from '@/api/apply.js'
	import ApplyFor from './component/ApplyFor.vue'
	import {
		baseUrl,
		baseImgUrl
	} from '@/config'
	import {
		getToken
	} from "@/utils/auth"
	export default {
		components: {
			ApplyFor
		},
		data() {
			return {
				FormData: {
					Tname: '',
					id: '',
				},
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名',
						}]
					},
					id: {
						rules: [{
								required: true,
								errorMessage: '请输入身份证',
							},
							{
								minLength: 18,
								maxLength: 18,
								errorMessage: '身份证长度在18位',
							}
						]
					},
				},
				scrollHeight: '',
				bottomBtnConfig: [{
					text: '提交申请',
					class: 'confirm',
					funcName: 'formSubmit'
				}],
				fileImage: {
					idCardFront: [],
					idCardBack: [],
					businessLicense: [],
					logo:[],
					commonSeal:[]
				},
				isApply: false,
				applyStatus: null,
				show: false,
				cityColumns: [],
				cityList: [],
				region: '',
				idCardPicA: null,
				idCardPicB: null,
				businessLicense: null,
				logo:null,
				commonSeal:null,
				defaultIndex: [],
			}
		},
		async onLoad() {
			await this.getCityList()
			this.scrollHeight = this.$store.getters.heightData.noTabMainHeight - 74 + 'px'
			this.getApplyStatus()
		},
		onShow() {
			
		},
		methods: {
			// 当前账号申请状态
			async getApplyStatus() {
				let res = await Apply.organizationStatus()
				if (res.code == 200) {
					// 0未申请 1审核中 2通过 3未通过
					if (res.data) {
						this.applyStatus = res.data.auditType
						if (res.data.auditType == 2) {
							uni.setNavigationBarTitle({
								title: '我的机构'
							})
							this.bottomBtnConfig[0].text = '修改资料'
							this.getInformationInfo(res.data.maintainCompanyId)
						} else if (res.data.auditType == 1) {
							uni.redirectTo({
								url: `/subPages/home/master/notExamine?title=企业入驻&msg=请您耐心等待`
							})
						} else {
							this.FormData = res.data
						}
					} else {
						this.applyStatus = 0
					}
					console.log(this.applyStatus, '当前申请状态');
				}
			},
			// 获取机构信息
			async getInformationInfo(id) {
				let response = await this.wbMaintainCompany(id)
				this.FormData = response.data
				let city = response.data.cityString ? `/${response.data.cityString}` : ''
				let county = response.data.countyString ? `/${response.data.countyString}` : ''
				this.region = (response.data.provinceString || '') + city + county

				// 设置城市列表
				this.cityColumns[0] = this.cityList?.filter(item => item.ctype == 1)
				this.cityColumns[1] = this.cityList?.filter(item => item.parentId == response.data.province)
				this.cityColumns[2] = this.cityList?.filter(item => item.parentId == response.data.city)
				this.cityColumns[0].forEach((item, index) => {
					if (item.id == response.data.province) {
						this.defaultIndex[0] = index
					}
				})
				this.cityColumns[1].forEach((item, index) => {
					if (item.id == response.data.city) {
						setTimeout(() => {
							this.defaultIndex[1] = index
						}, 0)
					}
				})
				this.cityColumns[2].forEach((item, index) => {
					if (item.id == response.data.county) {
						this.defaultIndex[2] = index
					}
				})

				// 图片赋值
				this.idCardPicA = response.data.idCardPicA
				if (response.data.idCardPicA) {
					this.fileImage.idCardFront.push({
						status: 'success',
						message: '',
						url: baseUrl + response.data.idCardPicA,
					})
				}
				this.idCardPicB = response.data.idCardPicB
				if (response.data.idCardPicB) {
					this.fileImage.idCardBack.push({
						status: 'success',
						message: '',
						url: baseUrl + response.data.idCardPicB
					})
				}
				this.businessLicense = response.data.businessLicense
				if (response.data.businessLicense) {
					this.fileImage.businessLicense.push({
						status: 'success',
						message: '',
						url: baseUrl + response.data.businessLicense
					})
				}
				this.logo = response.data.logo
				if (response.data.logo) {
					this.fileImage.logo.push({
						status: 'success',
						message: '',
						url: baseUrl + response.data.logo
					})
				}
				this.commonSeal = response.data.commonSeal
				if (response.data.commonSeal) {
					this.fileImage.commonSeal.push({
						status: 'success',
						message: '',
						url: baseUrl + response.data.commonSeal
					})
				}
			},
			// 获取城市信息
			async getCityList() {
				let res = await Home.getCity()
				if (res.code == 200) {
					this.cityList = res.data
					this.cityColumns[0] = res.data?.filter(item => item.ctype == 1)
					this.cityColumns[1] = res.data?.filter(item => item.parentId == 2)
					this.cityColumns[2] = res.data?.filter(item => item.parentId == 52)
					this.defaultIndex = [0, 0, 0]
					return res
				}
			},
			// 获取机构信息系
			async wbMaintainCompany(id) {
				let res = await Apply.wbMaintainCompany(id)
				if (res.code == 200) {
					return res
				}
			},

			// 新增图片
			async afterRead(event) {
				console.log(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileImage[`${event.name}`].length
				lists.map((item) => {
					this.fileImage[`${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				let res = await this.uploadFilePromise(event.file[0].url)
				if (res.code == 200) {
					let item = this.fileImage[`${event.name}`][fileListLen]
					this.fileImage[`${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: baseUrl + res.fileName,
					}))
					console.log(888, fileListLen, item, this.fileImage);
					switch (event.name) {
						case "idCardFront":
							this.idCardPicA = res.fileName
							break;
						case "idCardBack":
							this.idCardPicB = res.fileName
							break;
						case "businessLicense":
							this.businessLicense = res.fileName
							break;
						case "logo":
							this.logo = res.fileName
							break;
						case "commonSeal":
							this.commonSeal = res.fileName
							break;
					}
				}
			},
			formSubmit() {
				this.FormData.businessLicense = this.businessLicense
				this.FormData.idCardPicA = this.idCardPicA
				this.FormData.idCardPicB = this.idCardPicB
				this.FormData.logo = this.logo
				this.FormData.commonSeal = this.commonSeal
				this.$refs.masterEnterForm.validate().then(res => {
					Apply.putWbMaintainCompany(this.FormData).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '信息修改成功'
							})
							setTimeout(()=>{
								uni.navigateBack()
							},1000)
						}
					})
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			getImageValue(url){
				if(url){
					if(url.indexOf('prod-api')!=-1){
						console.log(url.split('prod-api'));
						return url.split('prod-api')[1]
					}else{
						return url
					}
				}else{
					return null
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseUrl + '/common/upload',
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + getToken()
						},
						formData: {},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			deletePic(v) {
				this.fileImage[`${v.name}`].splice(v.index, 1)
			},
			// 查看是否申请成功
			applySuccess(v) {
				this.applyStatus = v.auditType
				// this.FormData = v
			},
			// 城市改变选择
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				if (columnIndex === 0) {
					let parent = this.cityList.filter(item => item.parentId == value[0].id)
					picker.setColumnValues(1, this.cityList.filter(item => item.parentId == value[0].id))
					picker.setColumnValues(2, this.cityList.filter(item => item.parentId == parent[0].id))
				}
				if (columnIndex === 1) {
					picker.setColumnValues(2, this.cityList.filter(item => item.parentId == value[1].id))
				}
			},
			// 回调参数为包含columnIndex、value、values
			cityConfirm({
				value
			}) {
				let nameList = []
				value.forEach(item => {
					nameList.push(item.cname)
				})
				this.region = nameList.join('/')
				this.FormData.province = value[0].id
				this.FormData.provinceString = value[0].cname
				this.FormData.city = value[1].id
				this.FormData.cityString = value[1].cname
				this.FormData.county = value[2].id
				this.FormData.countyString = value[2].cname
				this.show = false
			},
		}
	}
</script>

<style scoped lang="scss">
	/deep/.placeholder-class {
		font-size: 26rpx;
		color: $main-font-auxiliary;
		line-height: 1;
		opacity: 0.8;
	}

	.main-content {
		width: 100%;
		height: 100%;
		padding: 20rpx 30rpx;

		.list-box {
			padding: 0 20rpx;
			border-radius: 16rpx;
			background: #ffffff;
			padding-top: 20rpx;

			.title {
				padding: 20rpx 0;
				margin-left: 15rpx;
				display: block;
				border-bottom: 2rpx solid #acacac;
				font-family: "PingFang SC";
				font-size: 28rpx;
				font-style: normal;
				font-weight: 600;
				line-height: 40rpx;
				opacity: 0.9;
			}
		}
	}

	.form-item-vertical {
		padding: 0;

		.label {
			color: #1a1a1a;
			font-size: 28rpx;
			padding: 20rpx 0;
			// &::before {
			// 	content: "*";
			// 	color: red;
			// 	font-size: 30rpx;
			// 	display: inline-block;
			// 	margin-right: 10rpx;
			// 	width: 5rpx;
			// 	height: 20rpx;
			// }
		}
	}

	.upload-box {
		height: 200rpx;
		width: 200rpx;
	}

	.upload-after {
		background: #F6F8FA;
		width: 150rpx;
		height: 150rpx;
		line-height: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>